# -*- coding:utf-8 -*-
from framework.interface.abstract_api import AbstractApi
from marshmallow import Schema, fields, validate
from datetime import datetime, timedelta
import pandas as pd
import numpy as np
from collections import namedtuple
from docx import Document
from docx.shared import Cm
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
from docx.enum.table import WD_TABLE_ALIGNMENT, WD_CELL_VERTICAL_ALIGNMENT
from docx.table import _Cell
from docx.oxml import OxmlElement
from docx.oxml.ns import qn
from docx2pdf import convert
from docx.shared import RGBColor
from docx.shared import Pt
from flask import request
import re
import subprocess

class PartZhaiyao(AbstractApi):
    """
    接口：PartZhaiyao
    文件名输入：part_zhaiyao
    该接口访问地址为：http://106.53.97.117:7777/v1/part-zhaiyao
    输入：
    功能：
    输出：
    """

    class  PostSchema(Schema):
        part_id = fields.Str(required=True)
        part_zhaiyao = fields.Str(required=True)

    def Set_cell_border(self,cell: _Cell, **kwargs):
        """
        设置单元格边框函数
        使用方法:
        Set_cell_border(
            cell,
            top={"sz": 12, "val": "single", "color": "#FF0000", "space": "0"},
            bottom={"sz": 12, "color": "#00FF00", "val": "single"},
            start={"sz": 24, "val": "dashed", "shadow": "true"},
            end={"sz": 12, "val": "dashed"},
        )
        传入参数有cell, 即单元格；top指上边框；bottom指下边框；start指左边框；end指右边框。
        "sz"指线的粗细程度；"val"指线型，比如单线，虚线等；"color"指颜色，颜色编码可百度；
        "space"指间隔，一般不设置，设置的值大于0会导致线错开；"shadow"指边框阴影
        """
        tc = cell._tc
        tcPr = tc.get_or_add_tcPr()

        tcBorders = tcPr.first_child_found_in("w:tcBorders")
        if tcBorders is None:
            tcBorders = OxmlElement('w:tcBorders')
            tcPr.append(tcBorders)

        for edge in ('start', 'top', 'end', 'bottom', 'insideH', 'insideV'):
            edge_data = kwargs.get(edge)
            if edge_data:
                tag = 'w:{}'.format(edge)

                element = tcBorders.find(qn(tag))
                if element is None:
                    element = OxmlElement(tag)
                    tcBorders.append(element)

                for key in ["sz", "val", "color", "space", "shadow"]:
                    if key in edge_data:
                        element.set(qn('w:{}'.format(key)), str(edge_data[key]))

    # 业务1
    def get_online_data(self):
        part_zhaiyao = request.get_json()['part_zhaiyao']
        part_id = request.get_json()['part_id']

        print(part_zhaiyao,part_id,"传过来的数据")

        # 使用正则表达式匹配方括号内的内容
        # 使用正则表达式匹配方括号内的内容
        matches = re.findall(r'\[(.*?)\]', part_zhaiyao, re.DOTALL)

        if matches:
            # 提取的内容保存在列表matches中，每个匹配项作为一个元素
            for match in matches:
                # 使用eval转换字符串为列表
                list_representation = eval(f'[{match}]')
                print(list_representation)
        else:
            list_representation=[]

        # 这里 输入正则化 提取出来的 数据项  封装为API接口 请求 正则参数 进行处理
        grades = list_representation
        document = Document()
        document.styles["Normal"].font.color.rgb = RGBColor(0, 0, 0)  # 设置正文全局颜色为黑色
        document.styles["Normal"].font.name = 'Times New Roman'
        document.styles["Normal"]._element.rPr.rFonts.set(qn('w:eastAsia'), '宋体')  # 如果想要设置中文字体，需要加上这一句
        '''原始数据'''
        title = document.add_paragraph()
        title.paragraph_format.space_after = Pt(18)  # 段前间距20磅
        title.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
        title.add_run("符号说明")
        for run in title.runs:
            run.font.size = Pt(18)
            run.font.name = '黑体'
            run._element.rPr.rFonts.set(qn('w:eastAsia'), '黑体')
            run.font.bold = True
        table = document.add_table(1, 3, style='Normal Table')
        heading_cells = table.rows[0].cells
        heading_cells[0].text = '符号表示'
        heading_cells[1].text = '符号说明'
        heading_cells[2].text = '符号单位'
        self.Set_cell_border(
            heading_cells[0],
            end={"sz": 6, "color": "#000000", "val": "single"},
        )
        self.Set_cell_border(
            heading_cells[0],
            top={"sz": 15, "color": "#000000", "val": "single"},
            bottom={"sz": 10, "color": "#000000", "val": "single"},
        )
        self.Set_cell_border(
            heading_cells[1],
            top={"sz": 15, "color": "#000000", "val": "single"},
            bottom={"sz": 10, "color": "#000000", "val": "single"},
        )

        self.Set_cell_border(
            heading_cells[2],
            top={"sz": 15, "color": "#000000", "val": "single"},
            bottom={"sz": 10, "color": "#000000", "val": "single"},
        )
        for name, chinese, intro in grades:
            cells = table.add_row().cells
            cells[0].text = name
            cells[1].text = str(chinese)
            cells[2].text = str(intro)
            self.Set_cell_border(
                cells[0],
                end={"sz": 6, "color": "#000000", "val": "single"},
            )
            for paragraph in cells[0].paragraphs:
                for run in paragraph.runs:
                    run.font.size = Pt(12)  # 设置字体大小为12磅
                    run.font.italic = True  # 将文字设置为斜体

            for paragraph in cells[2].paragraphs:
                for run in paragraph.runs:
                    run.font.size = Pt(12)  # 设置字体大小为12磅
                    run.font.italic = True  # 将文字设置为斜体
        # 设置表格的最后一条线

        self.Set_cell_border(
            cells[len(cells) - 2],
            bottom={"sz": 12, "color": "#000000", "val": "single"},
        )

        self.Set_cell_border(
            cells[len(cells) - 1],
            bottom={"sz": 12, "color": "#000000", "val": "single"},
        )

        self.Set_cell_border(
            cells[len(cells) - 3],
            bottom={"sz": 12, "color": "#000000", "val": "single"},
        )
        table.alignment = WD_TABLE_ALIGNMENT.CENTER  # 居中对齐
        cell = table.cell(0, 0)  # 左上角单元格
        for cell in table.row_cells(0):  # 第一行单元格
            cell.vertical_alignment = WD_CELL_VERTICAL_ALIGNMENT.CENTER  # 垂直对齐，居中

        for column in table.columns:  # 所有列
            for cell in column.cells:  # 所有单元格
                for paragraph in cell.paragraphs:  # 所有段落
                    paragraph.paragraph_format.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER  # 水平对齐，居中

        document.save(f'static/m{part_id}.docx')
        pdf_filename =f"static/m{part_id}.pdf"
        docx_filename =f"static/m{part_id}.docx"
        # output_path = r'test.pdf'
        # 将docx文档转换为PDF
        command = [
            'unoconv',
            '-f', 'pdf',
            '-o', pdf_filename,
            docx_filename
        ]
        subprocess.run(command, check=True)
        print("三线表书写成功")
        return {"msg":"摘要书写成功","status":list_representation,"url":f"http://106.53.97.117:7777/static/m{part_id}.pdf"}

    def handle_post_request(self):
        output1 = self.get_online_data()
        return output1



